package com.yzl.meeting.business.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class MyDbUtils {
    private static QueryRunner qr = null;
    private static DataSource dataSource = null;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        dataSource = new ComboPooledDataSource();
        qr = new QueryRunner(dataSource);
    }
    /**
     * 获取QueryRunner对象
     * @return
     */
    public static QueryRunner getQr(){
        return qr;
    }
    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection == null){
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

    /**
     * 开启事务
     * @throws SQLException
     */
    public static void beginTransaction() throws SQLException {
        Connection conn = threadLocal.get();
        if(conn != null){
            throw new SQLException("不要重复开启事务");
        }
        conn = getConnection();
        conn.setAutoCommit(false);

    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public static void commitTransaction() throws SQLException {
        Connection conn = threadLocal.get();
        if(conn == null){
            throw new SQLException("没有开启事务不能提交");
        }
        conn.commit();
        conn.close();
        threadLocal.remove();


    }

    /**
     * 回滚事务
     * @throws SQLException
     */
    public static void rollbackTransaction() throws SQLException {
        Connection conn = threadLocal.get();
        if(conn == null){
            throw new SQLException("没有开启事务不能回滚");
        }
        conn.rollback();
        conn.close();
        threadLocal.remove();
    }
}